package com.ybkj.daijia.server.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageInfo;
import com.ybkj.daijia.ServiceSetting;
import com.ybkj.daijia.serverUtils.ServiceUtil;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.serverUtils.UseAllDataUtil;
import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.errand.OrderType;
import com.ybkj.daijia.server.event.model.OperationLogEvent;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.DriverApply;
import com.ybkj.daijia.server.model.SmsTemplet;
import com.ybkj.daijia.server.model.SmsTemplet.SmsType;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.DriverApplyService;
import com.ybkj.daijia.server.service.DriverLevelService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.ErrandUpService;
import com.ybkj.daijia.server.service.SmsService;
import com.ybkj.daijia.server.service.SmsTempletService;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "driverapply")
public class DriverApplyController {

    private static final Logger logger = LoggerFactory.getLogger(DriverApplyController.class);

    @Autowired
    private DriverApplyService driverApplyService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private CompanyService companyService;
    @Autowired
    private DriverLevelService driverLevelService;
    @Autowired
    private SmsTempletService smsTempletService;
    @Autowired
    private SmsService smsService;
    @Autowired
    private SettingUtils settingUtils;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private ErrandUpService errandService;

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list() {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("driverapply")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("driverapply/list");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "driverApplyDatas", method = RequestMethod.GET)
    @ResponseBody
    public PageInfo<DriverApply> driverApplyDatas() {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("driverapply")) {
//            PageInfo<DriverApply> queryAll = driverApplyService.queryAll();
//            return queryAll;
        } else {
            throw new NoPermissionException();
        }
    return null;
    }

    @RequestMapping(value = "queryOrderType", method = RequestMethod.GET)
    @ResponseBody
    public Map<String, Object> queryOrderType(Long companyId) {
        Map<String, Object> map = new HashMap<String, Object>();
        List<OrderType> list = errandService.queryOrderType(companyId);

        map.put("success", true);
        map.put("data", list);

        return map;
    }


    @RequestMapping(value = "audit/{id}", method = RequestMethod.GET)
    public ModelAndView audit(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("driverapply")) {
            ModelAndView mv = new ModelAndView();
            //自动生成username
            String newUsername = driverService.findLastestDriver();
            mv.addObject("newUsername", newUsername);

            DriverApply local = driverApplyService.findOne(id);

            local.setPhone(UseAllDataUtil.useAllDataDriver(local.getPhone()));
            mv.addObject("driverapply", local);
            mv.addObject("levellist", driverLevelService.listMyAll());

            if (principal.isCompanyType()) {
                mv.addObject("companylist", companyService.findAll());
            } else {
                List<Company> companylist = new ArrayList<Company>();
                companylist.add(companyService.findOne(principal.getCompanyId()));
                mv.addObject("companylist", companylist);
            }
            ServiceSetting serviceSetting = ServiceUtil.checkOpen();
            if (serviceSetting.isPaotui()) {
                mv.addObject("detailedJobType",
                    errandService.queryOrderType(principal.getCompanyId()));
            }
            mv.setViewName("driverapply/audit");

            return mv;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "audit", method = RequestMethod.POST)
    public synchronized @ResponseBody
    Result<DriverApply> audit(
        Driver driver,
        @RequestParam("companyId") Long companyId,
        @RequestParam("applyId") Long applyId,
        @RequestParam(required = false, value = "driverLevelid") Long driverLevelid) {
        Result<DriverApply> result = new Result<DriverApply>();

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("driverapply")) {

            if (null != driverService.findByUsername(driver.getUsername())) {
                result.setSuccess(false);
                result.setMessage("工号'" + driver.getUsername() + "'已存在");
                return result;
            }
            if (null != driverService.findByIdCard(driver.getIdCard())) {
                result.setSuccess(false);
                result.setMessage("身份证'" + driver.getIdCard() + "'已存在");
                return result;
            }
            if (null != driverService.findByPhone(driver.getPhone())) {
                result.setSuccess(false);
                result.setMessage("手机号'" + driver.getPhone() + "'已存在");
                return result;
            }

            Company company = companyService.findOne(companyId);

            driver.setCompanyId(companyId);
            driver.setDriveTimes(0);
            driver.setIsFreeze(false);
            driver.setStatus(Driver.DRIVER_OFFLINE);
            driver.setVirtual(BigDecimal.ZERO);
            driver.setLongitude(company.getLongitude());
            driver.setLatitude(company.getLatitude());
            driver.setNamePinyin(toPinyin(driver.getRealname()));
            driver.setJobTime(new Date());

            String idCard = driver.getIdCard();
            String password = idCard.substring(idCard.length() - 4, idCard.length());

//			int password=RandomString.randomNum(4);
            logger.debug("密码" + password);
            Sha256Hash hash = new Sha256Hash(String.valueOf(password));
            driver.setPassword(hash.toBase64());

            ReactorVo rVo = new ReactorVo();
            rVo.setDriver(driver);
            rVo.setPassword(password + "");
            driverService.audit(driver, applyId);

            String detail = "【%s】审核了服务人员【" + driver.getUsername() + "】";
            OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
            applicationEventMulticaster.multicastEvent(operationLogEvent);

            Company driverCompany = companyService.findOne(driver.getCompanyId());
            Company finalCompany = driverCompany;
            Company main = companyService.getMain();
            Setting setting = settingUtils.get();
            if (!main.getId().equals(driverCompany.getId()) && setting.isSmsMainCompany()) {
                finalCompany = main;
            }

            try {
                String chenghu = "先生";
                if (driver.getGender().equals("女")) {
                    chenghu = "女士";
                }
                SmsTemplet templet = smsService
                    .findByAlias(finalCompany.getId(), SmsType.driverCreate);
                if (null != templet && StringUtils.isNotBlank(templet.getContent())) {
                    //smsService.sendSms(driver.getPhone(), "driverCreate", "{\"服务人员名\":\""+driver.getName()+"\",\"称呼\":\""+ chenghu+"\",\"公司名\":\""+company.getAbbreviation()+"\",\"服务人员账号\":\""+driver.getUsername()+"\",\"密码\":\""+password+"\"}",finalCompany.getId(),0,finalCompany.getSignName());
                    //短信发送（改）
                    JSONObject smsParam = new JSONObject();
                    smsParam.put("name", driver.getName());
                    smsParam.put("company", company.getAbbreviation());
                    smsParam.put("user", driver.getUsername());
                    smsParam.put("password", password);
                    smsService.sendSms(driver.getPhone(), templet.getTemplateId(),
                        smsParam.toJSONString(), finalCompany.getId(), 0,
                        finalCompany.getSignName());
                }
            } catch (Exception e) {
            }

            result.setSuccess(true);
            return result;
        } else {
            result.setSuccess(false);
            result.setMessage("您没有该权限");
            return result;
        }
    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> delete(Long id) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("driverapply")) {
            Result<Integer> result = new Result<Integer>();

            if (null != id) {
                DriverApply driverApply = driverApplyService.findOne(id);
                if (null != driverApply) {

                    String detail =
                        "【%s】删除了服务人员审核【" + driverApply.getRealname() + "(" + driverApply.getPhone()
                            + "】";

                    driverApplyService.delete(driverApply);

                    OperationLogEvent operationLogEvent = new OperationLogEvent(principal, detail);
                    applicationEventMulticaster.multicastEvent(operationLogEvent);

                    result.setSuccess(true);
                    result.setMessage("删除成功");
                } else {
                    result.setSuccess(false);
                    result.setMessage("没有可以删除的数据");
                }
            } else {
                result.setSuccess(false);
                result.setMessage("没有可以删除的数据");
            }

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    private String toPinyin(String zh) {

        if (StringUtils.isBlank(zh)) {
            return null;
        }

        HanyuPinyinOutputFormat outputFormat = new HanyuPinyinOutputFormat();
        outputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        outputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
        outputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);

        char ch[] = zh.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ch.length; i++) {
            if (Character.toString(ch[i]).matches("[\\u4E00-\\u9FA5]+")) {
                try {
                    String pinyinStrArray[] = PinyinHelper
                        .toHanyuPinyinStringArray(ch[i], outputFormat);

                    if ((null != pinyinStrArray) && (pinyinStrArray.length > 0)) {
                        sb.append(pinyinStrArray[0]);
                    }
                } catch (BadHanyuPinyinOutputFormatCombination e) {
                    e.printStackTrace();
                }
            } else {
                sb.append(ch[i]);
            }
        }

        return sb.toString();
    }

    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder dataBinder) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));

    }
}

